package com.lyl.common.validation.validator;

import cn.hutool.core.text.CharSequenceUtil;
import com.lyl.common.validation.annotation.ListValue;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author 罗亚龙
 * @date 2021/8/27 9:25
 */
public class ListValueConstraintValidator implements ConstraintValidator<ListValue, String> {

    /**
     * 存储枚举的值
     */
    private Set<String> set;

    /**
     * 是否必传
     */
    private boolean required;

    /**
     * 判断是否通过校验
     * @param value 入参传入的值
     * @param constraintValidatorContext 约束验证器上下文
     * @return true/false
     */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (CharSequenceUtil.isBlank(value)){
            return !required;
        }
        return set.contains(value);
    }

    /**
     * 用于接受注解上自定义的 属性
     * @param constraintAnnotation 约束注释
     */
    @Override
    public void initialize(ListValue constraintAnnotation) {
        //获取注解 的 values
        set = Stream.of(constraintAnnotation.value()).collect(Collectors.toSet());
        required = constraintAnnotation.required();
    }
}
